package com.cwl.config;

/**
 * 功能描述：
 *
 * @author cwledit
 * @date 2019/1/6
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.cwl.common.db.TableInfoKit;
import com.cwl.common.db.dialect.JbootMysqlDialect;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean(name = "dataSource")
    @Primary
    public DataSource primaryDataSource(Environment env) throws SQLException {
        // 配置真实数据源
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build(env, "spring.datasource");
        druidDataSource.setUsername(env.getProperty("spring.datasource.username"));
        druidDataSource.setPassword(env.getProperty("spring.datasource.password"));
        druidDataSource.setUrl(env.getProperty("spring.datasource.url"));
        druidDataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSourceMap.put("ds0", druidDataSource);
        return druidDataSource;

    }

    @Bean(name = "dataSourceProxy")
    public TransactionAwareDataSourceProxy dataSourceProxy(@Qualifier("dataSource") DataSource dataSource) {
        TransactionAwareDataSourceProxy dataSourceProxy = new TransactionAwareDataSourceProxy(dataSource);
        return dataSourceProxy;
    }
    @Bean(initMethod = "start",destroyMethod = "stop")
    public ActiveRecordPlugin activeRecordPlugin(@Qualifier("dataSourceProxy") DataSource dataSource){
        ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(dataSource);
        JFinal.me().getConstants().setDevMode(true);
        activeRecordPlugin.setDevMode(true);
        activeRecordPlugin.setShowSql(true);
        activeRecordPlugin.setContainerFactory(new CaseInsensitiveContainerFactory());
        activeRecordPlugin.setDialect(new JbootMysqlDialect());
        TableInfoKit.initTableInfos(activeRecordPlugin,"com.cwl.model.mc");
        return activeRecordPlugin;
    }

}
